package com.hu.system.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hu.common.exception.ServiceException;
import com.hu.common.utils.SecurityUtils;
import com.hu.common.utils.StringUtils;
import com.hu.system.mapper.StockOutboundMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.mapper.ProductInfoMapper;
import com.hu.system.domain.StockOutbound;
import com.hu.system.domain.ProductInfo;
import com.hu.system.service.IStockOutboundService;
import com.hu.system.service.IProductInfoService;

/**
 * 备货出库Service业务层处理
 *
 * @author hu
 * @date 2025-01-21
 */
@Service
public class StockOutboundServiceImpl implements IStockOutboundService {
    @Autowired
    private StockOutboundMapper stockOutboundMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private IProductInfoService productInfoService;

    /**
     * 查询备货出库列表
     *
     * @param stockOutbound 备货出库
     * @return 备货出库
     */
    @Override
    public List<StockOutbound> selectStockOutboundList(StockOutbound stockOutbound) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部
        if (userId != null && userId == 1L) {
            return stockOutboundMapper.selectStockOutboundList(stockOutbound);
        }

        // 普通用户根据店铺过滤
        // 保存并清除分页参数，避免被店铺ID查询消耗
        com.github.pagehelper.Page<?> savedPage = PageHelper.getLocalPage();
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        // 恢复分页参数
        if (savedPage != null) {
            PageHelper.startPage(savedPage.getPageNum(), savedPage.getPageSize(), savedPage.getOrderBy());
        }
        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 设置店铺ID过滤条件（支持多店铺）
        stockOutbound.getParams().put("shopIdList", shopIds);

        return stockOutboundMapper.selectStockOutboundList(stockOutbound);
    }

    /**
     * 查询备货出库详细信息
     *
     * @param outboundId 备货出库ID
     * @return 备货出库
     */
    @Override
    public StockOutbound selectStockOutboundByOutboundId(Long outboundId) {
        // 查询备货出库
        StockOutbound outbound = stockOutboundMapper.selectStockOutboundList(new StockOutbound() {{
            setOutboundId(outboundId);
        }}).stream().findFirst().orElse(null);

        if (outbound == null) {
            return null;
        }

        Long userId = SecurityUtils.getUserId();

        // 管理员可以查看全部
        if (userId != null && userId == 1L) {
            return outbound;
        }

        // 普通用户需要验证店铺权限
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || !shopIds.contains(outbound.getShopId())) {
            return null; // 无权限
        }

        return outbound;
    }

    /**
     * 新增备货出库
     *
     * @param stockOutbound 备货出库
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStockOutbound(StockOutbound stockOutbound) {
        // 根据SKU自动获取产品名称和所属店铺
        if (StringUtils.isNotEmpty(stockOutbound.getSku())) {
            ProductInfo product = productInfoMapper.selectProductInfoBySku(stockOutbound.getSku());
            if (product != null) {
                stockOutbound.setProductName(product.getProductName());
                stockOutbound.setShopId(product.getShopId()); // 从产品中获取店铺ID
            }
        }

        // 设置创建者
        stockOutbound.setCreateBy(SecurityUtils.getUsername());
        stockOutbound.setDelFlag("0");

        return stockOutboundMapper.insertStockOutbound(stockOutbound);
    }

    /**
     * 修改备货出库
     *
     * @param stockOutbound 备货出库
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStockOutbound(StockOutbound stockOutbound) {
        // 数据权限检查
        StockOutbound existingOutbound = selectStockOutboundByOutboundId(stockOutbound.getOutboundId());
        if (existingOutbound == null) {
            return 0; // 无权限或记录不存在
        }

        // 根据SKU自动更新产品名称和所属店铺
        if (StringUtils.isNotEmpty(stockOutbound.getSku())) {
            ProductInfo product = productInfoMapper.selectProductInfoBySku(stockOutbound.getSku());
            if (product != null) {
                stockOutbound.setProductName(product.getProductName());
                stockOutbound.setShopId(product.getShopId()); // 从产品中获取店铺ID
            }
        }

        // 设置更新者
        stockOutbound.setUpdateBy(SecurityUtils.getUsername());

        return stockOutboundMapper.updateStockOutbound(stockOutbound);
    }

    /**
     * 批量删除备货出库
     *
     * @param outboundIds 需要删除的备货出库ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStockOutboundByOutboundIds(Long[] outboundIds) {
        // 数据权限检查
        for (Long outboundId : outboundIds) {
            StockOutbound outbound = selectStockOutboundByOutboundId(outboundId);
            if (outbound == null) {
                return 0; // 无权限或记录不存在
            }
        }

        return stockOutboundMapper.deleteStockOutboundByOutboundIds(outboundIds);
    }

    /**
     * 根据备货单号和SKU查询备货出库
     *
     * @param stockOrderNo 备货单号
     * @param sku SKU编码
     * @return 备货出库对象
     */
    @Override
    public StockOutbound selectByStockOrderNoAndSku(String stockOrderNo, String sku) {
        return stockOutboundMapper.selectByStockOrderNoAndSku(stockOrderNo, sku);
    }
}

